package player

import (
	"GameServer/Common/utils"

	log "github.com/sirupsen/logrus"

	"GameServer/Common/data"
	"GameServer/Game/advert"
	"GameServer/Game/errors"
	"GameServer/Game/lib"
	"GameServer/Game/plog"
	"GameServer/Game/sp"
)

func (p *Player) HideShopReqRequest(req *sp.HideShopReqRequest) (res *sp.HideShopReqResponse) {
	us := p.User
	if us.MaxPos.LockBlockTid < 2 {
		res = &sp.HideShopReqResponse{}
		return
	}
	hideShop, err := lib.GetHideShop(us)
	if err != nil {
		log.WithFields(log.Fields{
			"uid":    us.Uid.Hex(),
			"method": "HideShopReqRequest",
			"data":   req,
		}).Error(err.Error())
		res = &sp.HideShopReqResponse{}
		return
	}

	if hideShop == nil {
		log.WithFields(log.Fields{
			"uid":    us.Uid.Hex(),
			"method": "HideShopReqRequest",
			"data":   req,
		}).Error("获取神秘商店出错")
		res = &sp.HideShopReqResponse{}
		return
	}

	res = &sp.HideShopReqResponse{
		ShopInfo: lib.FormatHideShopSp(hideShop),
	}
	return
}

func (p *Player) HideShopRefreshRequest(req *sp.HideShopRefreshRequest) (res *sp.HideShopRefreshResponse, err error) {
	hideShop, uProp, err := lib.HideShopReFresh(p.User)
	if err != nil {
		res = &sp.HideShopRefreshResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}

	res = &sp.HideShopRefreshResponse{
		ShopInfo: lib.FormatHideShopSp(hideShop),
	}
	p.TimelyUpdateProp(req.GetType(), uProp)
	utils.AsyncFunc(func() {
		p.UpdateProp(req.GetType(), uProp)
	})

	// 成就，记录刷新神秘商店次数。
	lib.AddAchievProgress(p.User, data.AchievementType.Refresh_hideShop, 1)

	// 有成就完成，进行通知
	achLst := lib.AchievComplete(p.User)
	if len(achLst) > 0 {
		p.Send(&sp.AchievementNoticeRequest{
			Lst: achLst,
		})
	}
	return
}

func (p *Player) HideShopBuyGoodsRequest(req *sp.HideShopBuyGoodsRequest) (res *sp.HideShopBuyGoodsResponse, err error) {
	us := p.User
	if req.Code == 1 {
		advert.Module.AddAdCnt(data.AdHideShop)                         // 统计神秘商店广告
		advert.Module.AddAdUser(us.Uid.Hex(), us.Name, data.AdHideShop) // 统计神秘商店广告
	}

	gid, uProp, resGoods, boxRes, err := lib.HideShopBuyGoods("HideShopBuyGoodsRequest", p.User, req.Id, req.Num, req.Code, p.Send)
	if err != nil {
		res = &sp.HideShopBuyGoodsResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	//添加购买隐藏商店道具的日志
	plog.Log_HideShop(p.User, gid, resGoods, uProp)
	// 成就，在神秘商店购买道具个数
	lib.AddAchievProgress(p.User, data.AchievementType.HideShop_purchase, 1)
	// 有成就完成，进行通知
	achLst := lib.AchievComplete(p.User)
	if len(achLst) > 0 {
		p.Send(&sp.AchievementNoticeRequest{
			Lst: achLst,
		})
	}
	res = &sp.HideShopBuyGoodsResponse{
		Gid:    gid,
		Res:    lib.FormatGoodsInfoSps(resGoods),
		BoxRes: lib.FormatBoxResSps(boxRes),
	}
	p.TimelyUpdateProp(req.GetType(), uProp)
	utils.AsyncFunc(func() {
		p.UpdateProp(req.GetType(), uProp)
	})
	return
}
